package com.aiyige.page.my.dynamicmanagement;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.db.dao.InfoModelDao;
import com.aiyige.base.db.dao.NormalVideoModelDao;
import com.aiyige.base.db.dao.PhotoModelDao;
import com.aiyige.base.db.dao.SpecialTopicDBModelDao;
import com.aiyige.base.db.table.InfoModel;
import com.aiyige.base.db.table.LearnVideoModel;
import com.aiyige.base.db.table.MajorCourseDBModel;
import com.aiyige.base.db.table.NormalVideoModel;
import com.aiyige.base.db.table.PhotoModel;
import com.aiyige.base.db.table.SpecialTopicDBModel;
import com.aiyige.base.eventbus.EventDMPublishProgressStatusUpdate;
import com.aiyige.base.eventbus.EventDMUploadUpdate;
import com.aiyige.base.eventbus.EventDeleteSearchMoment;
import com.aiyige.base.eventbus.EventPublishProgressStatusUpdate;
import com.aiyige.base.eventbus.EventServerChangeMomentStatus;
import com.aiyige.model.Page;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.page.my.dynamicmanagement.adapter.DMAdapter;
import com.aiyige.page.publish.publishresult.PublishResult;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.aiyige.utils.widget.CommonDataView;
import com.aiyige.utils.widget.LocalServerCommonDataView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.j256.ormlite.stmt.DeleteBuilder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;

@Route(path = ARouterConfig.DMPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class DMPage extends BaseActivity implements CommonDataView.RetrofitStub, LocalServerCommonDataView.OperationStub {
    public static final String TAG = DMPage.class.getSimpleName();
    public static final int SUBJECT_FILTER_ALL = 0;
    public static final int SUBJECT_FILTER_NORMAL_VIDEO = 1;
    public static final int SUBJECT_FILTER_PHOTO = 2;
    public static final int SUBJECT_FILTER_INFO = 3;
    public static final int SUBJECT_FILTER_SPECIAL_TOPIC = 4;

    public static final int STATUS_FILTER_ALL = 0;
    public static final int STATUS_FILTER_PUBLISHED = 1;
    public static final int STATUS_FILTER_NOT_PUBLISHED = 2;
    public static final int STATUS_FILTER_IN_REVIEW = 3;
    public static final int STATUS_FILTER_TAKEN_OFF_SHELF = 5;
    public static final int REQUEST_CODE_PUBLISH = 1;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.searchIcon)
    ImageView searchIcon;
    @BindView(R.id.inputEt)
    EditText inputEt;
    @BindView(R.id.inputEtClearBtn)
    ImageView inputEtClearBtn;
    @BindView(R.id.searchLayout)
    LinearLayout searchLayout;
    @BindView(R.id.subjectFilterTv)
    TextView subjectFilterTv;
    @BindView(R.id.subjectFilterLayout)
    FrameLayout subjectFilterLayout;
    @BindView(R.id.dividerLine1)
    View dividerLine1;
    @BindView(R.id.statusFilterTv)
    TextView statusFilterTv;
    @BindView(R.id.statusFilterLayout)
    FrameLayout statusFilterLayout;
    @BindView(R.id.cdv)
    LocalServerCommonDataView cdv;
    CommonBottomDialogFragment subjectFilterDialog;
    CommonBottomDialogFragment statusFilterDialog;
    @Autowired
    int statusFilter = STATUS_FILTER_ALL;
    @Autowired
    int subjectFilter = SUBJECT_FILTER_ALL;
    boolean shouldRefresh = false;
    DMAdapter dmAdapter;
    BroadcastReceiver broadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_dm);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        setAutoRegisterEventBus(true);
        initView();
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String action = intent.getAction();
                    switch (action) {
                        case PublishUtil.ACTION_UPLOAD_UPDATE:
                            EventBus.getDefault().post(new EventDMUploadUpdate());
                            break;
                        case PublishUtil.ACTION_PUBLISH_PROGRESS_STATUS_UPDATE:
                            EventBus.getDefault().post(new EventDMPublishProgressStatusUpdate());
                            break;
                    }
                } catch (Exception e) {

                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PublishUtil.ACTION_UPLOAD_UPDATE);
        intentFilter.addAction(PublishUtil.ACTION_PUBLISH_PROGRESS_STATUS_UPDATE);
        registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(broadcastReceiver);
        } catch (Exception e) {

        }
        super.onDestroy();
    }

    public void initView() {
        titleTv.setText(R.string.my_dynamic);
        subjectFilterDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.dm_subject_filter_dialog)
                .viewIdList(R.id.allBtn, R.id.normalVideoBtn, R.id.infoBtn, R.id.specialTopicBtn, R.id.photoBtn, R.id.cancelBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.allBtn:
                                if (subjectFilter == SUBJECT_FILTER_ALL) return;
                                subjectFilter = SUBJECT_FILTER_ALL;
                                break;
                            case R.id.normalVideoBtn:
                                if (subjectFilter == SUBJECT_FILTER_NORMAL_VIDEO) return;
                                subjectFilter = SUBJECT_FILTER_NORMAL_VIDEO;
                                break;
                            case R.id.infoBtn:
                                if (subjectFilter == SUBJECT_FILTER_INFO) return;
                                subjectFilter = SUBJECT_FILTER_INFO;
                                break;
                            case R.id.specialTopicBtn:
                                if (subjectFilter == SUBJECT_FILTER_SPECIAL_TOPIC) return;
                                subjectFilter = SUBJECT_FILTER_SPECIAL_TOPIC;
                                break;
                            case R.id.photoBtn:
                                if (subjectFilter == SUBJECT_FILTER_PHOTO) return;
                                subjectFilter = SUBJECT_FILTER_PHOTO;
                                break;
                            default:
                                return;
                        }
                        shouldRefresh = true;
                        updateSubjectFilterTv();
                        cdv.refresh();
                    }
                })
                .build();
        statusFilterDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.dm_status_filter_dialog)
                .viewIdList(R.id.allBtn, R.id.publishedBtn, R.id.notPublishedBtn, R.id.takenOffShelfBtn, R.id.cancelBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.allBtn:
                                if (statusFilter == STATUS_FILTER_ALL) return;
                                statusFilter = STATUS_FILTER_ALL;
                                break;
                            case R.id.publishedBtn:
                                if (statusFilter == STATUS_FILTER_PUBLISHED) return;
                                statusFilter = STATUS_FILTER_PUBLISHED;
                                break;
                            case R.id.notPublishedBtn:
                                if (statusFilter == STATUS_FILTER_NOT_PUBLISHED) return;
                                statusFilter = STATUS_FILTER_NOT_PUBLISHED;
                                break;
                            case R.id.takenOffShelfBtn:
                                if (statusFilter == STATUS_FILTER_TAKEN_OFF_SHELF) return;
                                statusFilter = STATUS_FILTER_TAKEN_OFF_SHELF;
                                break;
                            default:
                                return;
                        }
                        shouldRefresh = true;
                        updateStatusFilterTv();
                        cdv.refresh();
                    }
                })
                .build();

        dmAdapter = new DMAdapter(this);
        cdv.config(dmAdapter, this, this);
        dmAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MultiItemEntity entity = dmAdapter.getItem(position);
                switch (entity.getItemType()) {
                    case PublishUtil.PARENT_TYPE_PHOTO:
                        PhotoModel photoModel = (PhotoModel) entity;
                        switch (photoModel.getProgressStatus()) {
                            case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                            case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                            case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                            case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                            case PublishUtil.PROGRESS_STATUS_UPLOADING:
                            case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                            case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                            case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                                ARouter.getInstance().build(ARouterConfig.UploadFilePage)
                                        .withString("parentId", photoModel.getId())
                                        .withInt("parentType", PublishUtil.PARENT_TYPE_PHOTO)
                                        .navigation();
                                break;
                            default:
                                Router.start(photoModel.getRouter());
                                break;
                        }
                        break;
                    case PublishUtil.PARENT_TYPE_NORMAL_VIDEO:
                        NormalVideoModel normalVideoModel = (NormalVideoModel) entity;
                        switch (normalVideoModel.getProgressStatus()) {
                            case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                            case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                            case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                            case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                            case PublishUtil.PROGRESS_STATUS_UPLOADING:
                            case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                            case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                            case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                                ARouter.getInstance().build(ARouterConfig.UploadFilePage)
                                        .withString("parentId", normalVideoModel.getId())
                                        .withInt("parentType", PublishUtil.PARENT_TYPE_NORMAL_VIDEO)
                                        .navigation();
                                break;
                            case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                                ToastX.show(R.string.server_transcoding);
                                break;
                            default:
                                Router.start(normalVideoModel.getRouter());
                                break;
                        }
                        break;
                    case PublishUtil.PARENT_TYPE_INFO:
                        InfoModel infoModel = (InfoModel) entity;
                        switch (infoModel.getProgressStatus()) {
                            case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                            case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                            case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                            case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                            case PublishUtil.PROGRESS_STATUS_UPLOADING:
                            case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                            case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                            case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                                ARouter.getInstance()
                                        .build(ARouterConfig.UploadFilePage)
                                        .withString("parentId", infoModel.getId())
                                        .withInt("parentType", PublishUtil.PARENT_TYPE_INFO)
                                        .navigation();
                                break;
                            case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                                ToastX.show(R.string.server_transcoding);
                                break;
                            default:
                                Router.start(infoModel.getRouter());
                                break;
                        }
                        break;

                    case PublishUtil.PARENT_TYPE_SPECIAL_TOPIC:
                        SpecialTopicDBModel specialTopicDBModel = (SpecialTopicDBModel) entity;
                        switch (specialTopicDBModel.getProgressStatus()) {
                            case PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE:
                            case PublishUtil.PROGRESS_STATUS_TRANSCODE_FINISH:
                            case PublishUtil.PROGRESS_STATUS_TRANSCODE_FAILED:
                            case PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD:
                            case PublishUtil.PROGRESS_STATUS_UPLOADING:
                            case PublishUtil.PROGRESS_STATUS_UPLOAD_FINISH:
                            case PublishUtil.PROGRESS_STATUS_SUBMITTING:
                            case PublishUtil.PROGRESS_STATUS_SUBMIT_FAILED:
                                ARouter.getInstance()
                                        .build(ARouterConfig.UploadFilePage)
                                        .withString("parentId", specialTopicDBModel.getId())
                                        .withInt("parentType", PublishUtil.PARENT_TYPE_SPECIAL_TOPIC)
                                        .navigation();
                                break;
                            case PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING:
                                ToastX.show(R.string.server_transcoding);
                                break;
                            default:
                                Router.start(specialTopicDBModel.getRouter());
                                break;
                        }
                        break;
                }
            }
        });
        inputEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String searchStr = inputEt.getText().toString();
                    if (!TextUtils.isEmpty(searchStr.trim())) {
                        ARouter.getInstance()
                                .build(ARouterConfig.DMSearchGroupPage)
                                .withString("keyword", searchStr.trim())
                                .navigation();
                    }
                    return true;
                }
                return false;
            }
        });

        inputEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                inputEtClearBtn.setVisibility(s.length() == 0 ? View.INVISIBLE : View.VISIBLE);
            }
        });
        updateStatusFilterTv();
        updateSubjectFilterTv();
        cdv.doRefreshRequest();
    }

    private void updateSubjectFilterTv() {
        switch (subjectFilter) {
            case SUBJECT_FILTER_ALL:
                subjectFilterTv.setText(R.string.all_dynamic);
                break;
            case SUBJECT_FILTER_INFO:
                subjectFilterTv.setText(R.string.info);
                break;
            case SUBJECT_FILTER_NORMAL_VIDEO:
                subjectFilterTv.setText(R.string.video);
                break;
            case SUBJECT_FILTER_PHOTO:
                subjectFilterTv.setText(R.string.photo);
                break;
            case SUBJECT_FILTER_SPECIAL_TOPIC:
                subjectFilterTv.setText(R.string.special_topic);
                break;
        }
    }

    private void updateStatusFilterTv() {
        switch (statusFilter) {
            case STATUS_FILTER_ALL:
                statusFilterTv.setText(R.string.all_status);
                break;
            case STATUS_FILTER_IN_REVIEW:
                statusFilterTv.setText(R.string.in_review);
                break;
            case STATUS_FILTER_NOT_PUBLISHED:
                statusFilterTv.setText(R.string.not_published);
                break;
            case STATUS_FILTER_PUBLISHED:
                statusFilterTv.setText(R.string.published);
                break;
            case STATUS_FILTER_TAKEN_OFF_SHELF:
                statusFilterTv.setText(R.string.taken_off_shelf_view_reason);
                break;
        }
    }


    @OnClick({R.id.titleBackBtn, R.id.statusFilterLayout, R.id.subjectFilterLayout, R.id.inputEtClearBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.inputEtClearBtn:
                inputEt.setText("");
                break;
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.statusFilterLayout:
                statusFilterDialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.subjectFilterLayout:
                subjectFilterDialog.show(getSupportFragmentManager(), "");
                break;
        }
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        List<String> subjectList = new ArrayList<>();
        switch (subjectFilter) {
            case SUBJECT_FILTER_ALL: {
                subjectList = Arrays.asList(Moment.SUBJECT_VIDEO, Moment.SUBJECT_ARTICLE, Moment.SUBJECT_PHOTO, Moment.SUBJECT_SPECIAL_TOPIC);
                break;
            }
            case SUBJECT_FILTER_INFO: {
                subjectList = Arrays.asList(Moment.SUBJECT_ARTICLE);
                break;
            }

            case SUBJECT_FILTER_SPECIAL_TOPIC: {
                subjectList = Arrays.asList(Moment.SUBJECT_SPECIAL_TOPIC);
                break;
            }
            case SUBJECT_FILTER_PHOTO: {
                subjectList = Arrays.asList(Moment.SUBJECT_PHOTO);
                break;
            }
            case SUBJECT_FILTER_NORMAL_VIDEO: {
                subjectList = Arrays.asList(Moment.SUBJECT_VIDEO);
                break;
            }
        }
        return ApiManager.getService().dynamicManagementMoment(20, currentPage, subjectList, statusFilter);
    }


    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent(), Moment.class));
            }
            for (Moment moment : momentList) {
                Moment record = new Moment(moment);
                switch (record.getSubjectIndex()) {
                    case Moment.SUBJECT_ARTICLE_INDEX:
                        resultList.add(InfoModel.parse(record));
                        break;
                    case Moment.SUBJECT_SPECIAL_TOPIC_INDEX:
                        resultList.add(SpecialTopicDBModel.parse(record));
                        break;
                    case Moment.SUBJECT_PHOTO_INDEX:
                        resultList.add(PhotoModel.parse(record));
                        break;
                    case Moment.SUBJECT_VIDEO_INDEX:
                        resultList.add(NormalVideoModel.parse(record));
                        break;
                }
            }
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }


    @Override
    public List query() {
        if (statusFilter != STATUS_FILTER_ALL && statusFilter != STATUS_FILTER_NOT_PUBLISHED) {
            return new LinkedList();
        }
        try {
            DeleteBuilder<InfoModel, String> deleteBuilder = InfoModelDao.getDao().deleteBuilder();
            deleteBuilder.where()
                    .eq(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                    .or()
                    .eq(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                    .or()
                    .eq(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                    .or()
                    .eq(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                    .or()
                    .eq(InfoModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT);
            deleteBuilder.delete();
        } catch (Exception e) {
        }

        try {
            DeleteBuilder<SpecialTopicDBModel, String> deleteBuilder = SpecialTopicDBModelDao.getDao().deleteBuilder();
            deleteBuilder.where()
                    .eq(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                    .or()
                    .eq(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                    .or()
                    .eq(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                    .or()
                    .eq(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                    .or()
                    .eq(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT);
            deleteBuilder.delete();
        } catch (Exception e) {
        }


        try {
            DeleteBuilder<NormalVideoModel, String> deleteBuilder = NormalVideoModelDao.getDao().deleteBuilder();
            deleteBuilder.where()
                    .eq(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                    .or()
                    .eq(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                    .or()
                    .eq(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                    .or()
                    .eq(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                    .or()
                    .eq(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT);
            deleteBuilder.delete();
        } catch (Exception e) {
        }

        try {
            DeleteBuilder<PhotoModel, String> deleteBuilder = PhotoModelDao.getDao().deleteBuilder();
            deleteBuilder.where()
                    .eq(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                    .or()
                    .eq(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                    .or()
                    .eq(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                    .or()
                    .eq(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                    .or()
                    .eq(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT);
            deleteBuilder.delete();
        } catch (Exception e) {
        }


        List<MultiItemEntity> multiItemEntityList = new LinkedList<>();
        switch (subjectFilter) {
            case SUBJECT_FILTER_ALL: {
                try {
                    multiItemEntityList.addAll(InfoModelDao.getDao().queryBuilder()
                            .where()
                            .eq(LearnVideoModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                            .and()
                            .ne(LearnVideoModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_REJECT)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                            .query());
                } catch (Exception e) {

                }

                try {
                    multiItemEntityList.addAll(SpecialTopicDBModelDao.getDao().queryBuilder()
                            .where()
                            .eq(SpecialTopicDBModel.USER_ID, AccountUtil.getCurrentUser().getId())
                            .and()
                            .ne(SpecialTopicDBModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_DELETE)
                            .and()
                            .ne(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                            .and()
                            .ne(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                            .and()
                            .ne(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                            .and()
                            .ne(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT)
                            .and()
                            .ne(SpecialTopicDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                            .query());
                } catch (Exception e) {

                }


                try {
                    multiItemEntityList.addAll(PhotoModelDao.getDao().queryBuilder()
                            .where()
                            .eq(MajorCourseDBModel.USER_ID, AccountUtil.getCurrentUser().getId())
                            .and()
                            .ne(MajorCourseDBModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_DELETE)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                            .query());
                } catch (Exception e) {

                }

                try {
                    multiItemEntityList.addAll(NormalVideoModelDao.getDao().queryBuilder()
                            .where()
                            .eq(MajorCourseDBModel.USER_ID, AccountUtil.getCurrentUser().getId())
                            .and()
                            .ne(MajorCourseDBModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_DELETE)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                            .query());
                } catch (Exception e) {

                }
                break;
            }
            case SUBJECT_FILTER_INFO: {
                try {
                    multiItemEntityList.addAll(InfoModelDao.getDao().queryBuilder()
                            .where()
                            .eq(MajorCourseDBModel.USER_ID, AccountUtil.getCurrentUser().getId())
                            .and()
                            .ne(MajorCourseDBModel.CONTROL_OPTION, PublishUtil.CONTROL_OPTION_DELETE)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_REJECT)
                            .and()
                            .ne(MajorCourseDBModel.PROGRESS_STATUS, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                            .query());
                } catch (Exception e) {

                }
                break;
            }
            case SUBJECT_FILTER_PHOTO: {
                try {
                    multiItemEntityList.addAll(PhotoModelDao.getDao().queryBuilder()
                            .where()
                            .eq(LearnVideoModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                            .and()
                            .ne(LearnVideoModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_REJECT)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                            .query());
                } catch (Exception e) {

                }
                break;
            }
            case SUBJECT_FILTER_NORMAL_VIDEO: {
                try {
                    multiItemEntityList.addAll(NormalVideoModelDao.getDao().queryBuilder()
                            .where()
                            .eq(LearnVideoModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                            .and()
                            .ne(LearnVideoModel.CONTROL_OPTION_FIELD, PublishUtil.CONTROL_OPTION_DELETE)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_PUBLISHED)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_IN_REVIEW)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_REJECT)
                            .and()
                            .ne(LearnVideoModel.PROGRESS_STATUS_FIELD, PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING)
                            .query());
                } catch (Exception e) {

                }
                break;
            }
        }
        return multiItemEntityList;
    }

    @Override
    public int compare(Object o1, Object o2) {
        long o1ReleaseDate = 0;
        long o2ReleaseDate = 0;
        MultiItemEntity item1 = (MultiItemEntity) o1;
        MultiItemEntity item2 = (MultiItemEntity) o2;
        switch (item1.getItemType()) {
            case PublishUtil.PARENT_TYPE_NORMAL_VIDEO:
                o1ReleaseDate = ((NormalVideoModel) item1).getReleaseDate();
                break;
            case PublishUtil.PARENT_TYPE_INFO:
                o1ReleaseDate = ((InfoModel) item1).getReleaseDate();
                break;
            case PublishUtil.PARENT_TYPE_SPECIAL_TOPIC:
                o1ReleaseDate = ((SpecialTopicDBModel) item1).getReleaseDate();
                break;
            case PublishUtil.PARENT_TYPE_PHOTO:
                o1ReleaseDate = ((PhotoModel) item1).getReleaseDate();
                break;
        }
        switch (item2.getItemType()) {
            case PublishUtil.PARENT_TYPE_NORMAL_VIDEO:
                o2ReleaseDate = ((NormalVideoModel) item2).getReleaseDate();
                break;
            case PublishUtil.PARENT_TYPE_INFO:
                o2ReleaseDate = ((InfoModel) item2).getReleaseDate();
                break;
            case PublishUtil.PARENT_TYPE_SPECIAL_TOPIC:
                o2ReleaseDate = ((SpecialTopicDBModel) item2).getReleaseDate();
                break;
            case PublishUtil.PARENT_TYPE_PHOTO:
                o2ReleaseDate = ((PhotoModel) item2).getReleaseDate();
                break;
        }
        long diff = o2ReleaseDate - o1ReleaseDate;
        if (diff > 0) {
            return 1;
        } else if (diff == 0) {
            return 0;
        } else {
            return -1;
        }
    }

    @Override
    public boolean equal(Object o1, Object o2) {
        MultiItemEntity item1 = (MultiItemEntity) o1;
        MultiItemEntity item2 = (MultiItemEntity) o2;
        if (item1.getItemType() != item2.getItemType()) {
            return false;
        }
        switch (item1.getItemType()) {
            case PublishUtil.PARENT_TYPE_SPECIAL_TOPIC: {
                SpecialTopicDBModel model1 = (SpecialTopicDBModel) item1;
                SpecialTopicDBModel model2 = (SpecialTopicDBModel) item2;
                if (!TextUtils.isEmpty(model1.getId()) && TextUtils.isEmpty(model2.getId())) {
                    return model1.getId().equals(model2.getId());
                } else if (!TextUtils.isEmpty(model1.getGoodsId()) && !TextUtils.isEmpty(model2.getGoodsId())) {
                    return model1.getGoodsId().equals(model2.getGoodsId());
                } else {
                    return false;
                }
            }

            case PublishUtil.PARENT_TYPE_INFO: {
                InfoModel model1 = (InfoModel) item1;
                InfoModel model2 = (InfoModel) item2;
                if (!TextUtils.isEmpty(model1.getId()) && TextUtils.isEmpty(model2.getId())) {
                    return model1.getId().equals(model2.getId());
                } else if (!TextUtils.isEmpty(model1.getGoodsId()) && !TextUtils.isEmpty(model2.getGoodsId())) {
                    return model1.getGoodsId().equals(model2.getGoodsId());
                } else {
                    return false;
                }
            }
            case PublishUtil.PARENT_TYPE_NORMAL_VIDEO: {
                NormalVideoModel model1 = (NormalVideoModel) item1;
                NormalVideoModel model2 = (NormalVideoModel) item2;
                if (!TextUtils.isEmpty(model1.getId()) && TextUtils.isEmpty(model2.getId())) {
                    return model1.getId().equals(model2.getId());
                } else if (!TextUtils.isEmpty(model1.getGoodsId()) && !TextUtils.isEmpty(model2.getGoodsId())) {
                    return model1.getGoodsId().equals(model2.getGoodsId());
                } else {
                    return false;
                }
            }
            case PublishUtil.PARENT_TYPE_PHOTO: {
                PhotoModel model1 = (PhotoModel) item1;
                PhotoModel model2 = (PhotoModel) item2;
                if (!TextUtils.isEmpty(model1.getId()) && TextUtils.isEmpty(model2.getId())) {
                    return model1.getId().equals(model2.getId());
                } else if (!TextUtils.isEmpty(model1.getGoodsId()) && !TextUtils.isEmpty(model2.getGoodsId())) {
                    return model1.getGoodsId().equals(model2.getGoodsId());
                } else {
                    return false;
                }
            }
            default:
                return false;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventDMUploadUpdate event) {
        dmAdapter.getEventBus().post(new EventPublishProgressStatusUpdate());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventDMPublishProgressStatusUpdate event) {
        dmAdapter.getEventBus().post(new EventPublishProgressStatusUpdate());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventServerChangeMomentStatus event) {
        if (event.getSubject().equals(Moment.SUBJECT_VIDEO)|| event.getSubject().equals(Moment.SUBJECT_SPECIAL_TOPIC) || event.getSubject().equals(Moment.SUBJECT_ARTICLE) || event.getSubject().equals(Moment.SUBJECT_PHOTO)) {
            int progressStatus;
            switch (event.getTargetStatus()) {
                case Moment.STATUS_IN_REVIEW:
                    progressStatus = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                    break;
                case Moment.STATUS_REJECT:
                    progressStatus = PublishUtil.PROGRESS_STATUS_REJECT;
                    break;
                case Moment.STATUS_PUT_ON:
                    progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                    break;
                case Moment.STATUS_SAVE:
                    progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                    break;
                case Moment.STATUS_REVIEW_PASSED:
                    progressStatus = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                    break;
                case Moment.STATUS_GET_OFF:
                    progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                    break;
                case Moment.STATUS_TRANSCODING:
                    progressStatus = PublishUtil.PROGRESS_STATUS_SERVER_TRANSCODING;
                    break;
                default:
                    progressStatus = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                    break;
            }
            int upLimit = dmAdapter.getData().size();
            for (int i = 0; i < upLimit; ++i) {
                MultiItemEntity entity = dmAdapter.getItem(i);
                switch (entity.getItemType()) {
                    case PublishUtil.PARENT_TYPE_NORMAL_VIDEO: {
                        NormalVideoModel normalVideoModel = (NormalVideoModel) entity;
                        if (event.getMomentId().equals(normalVideoModel.getGoodsId())) {
                            normalVideoModel.setProgressStatus(progressStatus);
                            normalVideoModel.setRejectReason(event.getMessage());
                            try {
                                NormalVideoModelDao.getDao().update(normalVideoModel);
                            } catch (Exception e) {
                            }
                            dmAdapter.setData(i, normalVideoModel);
                            return;
                        }
                        break;
                    }

                    case PublishUtil.PARENT_TYPE_INFO: {
                        InfoModel infoModel = (InfoModel) entity;
                        if (event.getMomentId().equals(infoModel.getGoodsId())) {
                            infoModel.setProgressStatus(progressStatus);
                            infoModel.setRejectReason(event.getMessage());
                            try {
                                InfoModelDao.getDao().update(infoModel);
                            } catch (SQLException e) {
                            }
                            dmAdapter.setData(i, infoModel);
                            return;
                        }
                        break;
                    }

                    case PublishUtil.PARENT_TYPE_SPECIAL_TOPIC: {
                        SpecialTopicDBModel specialTopicDBModel = (SpecialTopicDBModel) entity;
                        if (event.getMomentId().equals(specialTopicDBModel.getGoodsId())) {
                            specialTopicDBModel.setProgressStatus(progressStatus);
                            specialTopicDBModel.setRejectReason(event.getMessage());
                            try {
                                SpecialTopicDBModelDao.getDao().update(specialTopicDBModel);
                            } catch (SQLException e) {
                            }
                            dmAdapter.setData(i, specialTopicDBModel);
                            return;
                        }
                        break;
                    }


                    case PublishUtil.PARENT_TYPE_PHOTO: {
                        PhotoModel photoModel = (PhotoModel) entity;
                        if (event.getMomentId().equals(photoModel.getGoodsId())) {
                            photoModel.setProgressStatus(progressStatus);
                            photoModel.setRejectReason(event.getMessage());
                            try {
                                PhotoModelDao.getDao().update(photoModel);
                            } catch (SQLException e) {
                            }
                            dmAdapter.setData(i, photoModel);
                            return;
                        }
                        break;
                    }
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_PUBLISH:
                PublishResult publishResult = PublishResult.obtainPublishResult(data);
                if (publishResult != null) {
                    publishResult.setTargetTab(PublishResult.TARGET_TAB_INVALID);
                }
                PublishResult.handlePublishResult(this, publishResult);
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventDeleteSearchMoment event) {
        switch (event.getParentType()) {
            case PublishUtil.PARENT_TYPE_SPECIAL_TOPIC:
            case PublishUtil.PARENT_TYPE_INFO:
            case PublishUtil.PARENT_TYPE_NORMAL_VIDEO:
            case PublishUtil.PARENT_TYPE_PHOTO: {
                if (!TextUtils.isEmpty(event.getServerId())) {
                    int upLimit = dmAdapter.getData().size();
                    for (int i = 0; i < upLimit; ++i) {
                        if (event.getServerId().equals(PublishUtil.extractServerIdFromMultiItemEntity(dmAdapter.getItem(i)))) {
                            dmAdapter.remove(i);
                            return;
                        }
                    }
                }
                break;
            }
        }
    }
}
